<template>
  <a-modal
    v-model:open="visible"
    title="选择收藏夹"
    width="400px"
    :confirm-loading="loading"
    @ok="handleConfirm"
  >
    <a-list v-if="folderList.length > 0">
      <a-checkbox-group
        v-model:value="selectedFolderIds"
        style="display: flex; flex-direction: column"
      >
        <a-checkbox
          v-for="folder in folderList"
          :key="folder.id"
          :value="folder.id"
          style="margin-bottom: 8px"
        >
          {{ folder.typeName }}
        </a-checkbox>
      </a-checkbox-group>
    </a-list>

    <template #footer>
      <a-button @click="visible = false">取消</a-button>
      <a-button type="primary" :loading="loading" @click="handleConfirm">确定</a-button>
    </template>
  </a-modal>
</template>

<script setup>
import { ref } from 'vue'
import { message } from 'ant-design-vue'

import { listByUserId1, } from '@/api/bizQuestionUserCollectionController'
import{add1,addMulti} from '@/api/bizQuestionCollectionController'
const visible = ref(false)
const folderList = ref([])
const selectedFolderIds = ref([])
const currentQuestion = ref(null)
const loading = ref(false)

function openDialog(question) {
  currentQuestion.value = question
  visible.value = true
  selectedFolderIds.value = []
  fetchFolders()
}

async function fetchFolders() {
  try {
    const res = await listByUserId1()
    if (res?.data?.code === 0) {
      folderList.value = res.data.data || []
    } else {
      message.error(res?.data?.message || '获取收藏夹失败')
    }
  } catch (error) {
    message.error('请求失败，请检查网络或稍后再试')
    console.error('listByUserId1 error:', error)
  }
}

async function handleConfirm() {
  if (selectedFolderIds.value.length === 0) {
    message.warning('请至少选择一个收藏夹')
    return
  }

  //loading.value = true
  try {
    const res = await addMulti({
      questionId: currentQuestion.value.id,
      folderId: selectedFolderIds.value  // 直接传数组
    })

    if (res?.data?.code === 0) {
      message.success('收藏成功')
      visible.value = false
    } else {
      message.error(res?.data.data || '收藏失败')
    }
  } catch (e) {
    message.error('收藏请求出错')
    console.error(e)
  } finally {
    visible.value = false
  }

}
defineExpose({ openDialog })
</script>
